package cn.zxhysy.booksmall.controller;

import cn.zxhysy.booksmall.entity.User;
import cn.zxhysy.booksmall.utils.ApiJSONResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.UUID;

/**
 * @className: UserController
 * @description:
 */
@Api(value = "用户接口", tags = "用户操作")
@RestController
@RequestMapping(value = {"/user", "/api/user"})
public class UserController {
    private final BasicController basicController;

    @Autowired
    public UserController(BasicController basicController) {
        this.basicController = basicController;
    }

    /**
     * 用户登录
     * @param user 用户对象
     * @return 成功与否
     */
    @ApiOperation(value = "用户登录", notes = "用户登录")
    @PostMapping("/login")
    public ApiJSONResult login(@ApiParam(value = "用户对象", required = true) @RequestBody User user, HttpServletRequest request) throws Exception {
        if (StringUtils.isBlank(user.getName()) || StringUtils.isBlank(user.getPassword())) {
            return ApiJSONResult.errorMsg("账号和密码不能为空");
        }
        User loginResult = basicController.userService.login(user);
        if (null == loginResult) {
            return ApiJSONResult.errorMsg("账号或密码错误");
        }
        loginResult.setPassword("");
        String uniqueToken = UUID.randomUUID().toString();
        request.getSession().setAttribute(BasicController.USER_REDIS_SESSION, uniqueToken);
        request.getSession().setAttribute(BasicController.CONCRETE_NAME, loginResult.getConcreteName());
        return ApiJSONResult.ok(loginResult);
    }

    /**
     * 用户登录
     */
    @ApiOperation(value = "用户登录", notes = "用户登录")
    @GetMapping("/login/{userName}/{password}")
    public ApiJSONResult login(@PathVariable String userName, @PathVariable String password, HttpServletRequest request) throws Exception {

        if (StringUtils.isNoneBlank(userName, password)) {
            User user = new User();
            user.setPassword(password);
            user.setName(userName);
            return login(user, request);
        }
        return ApiJSONResult.errorMsg("登录失败");
    }
}
